var commonjs = require("../../utils/common.js");
var app = getApp();
Page({
  data: {
    in_theaters: {},
    coming_soon: {},
    top250: {}
  },
  onLoad: function (options) {
    var that = this;
    var in_theaters_url = app.globalDatas.doubanBaseUrl + "v2/movie/in_theaters?start=0&count=3";
    var coming_soon_url = app.globalDatas.doubanBaseUrl + "v2/movie/coming_soon?start=0&count=3";
    var top250_url = app.globalDatas.doubanBaseUrl + "v2/movie/top250?start=0&count=3";

    this.requestDoubanMovieDatas(in_theaters_url, "in_theaters");
    this.requestDoubanMovieDatas(coming_soon_url, "coming_soon");
    this.requestDoubanMovieDatas(top250_url, "top250");
  },
  
  requestDoubanMovieDatas(url, key) {
    commonjs.showLoadingToast();
    var that = this;
    commonjs.http(url, function (data) {
      wx.hideToast();
      that.processDoubanData(data, key);
    },null);
  },

  processDoubanData(data, key) {
    var subjects = data.subjects;
    var movies = [];
    for (var i = 0; i < subjects.length; i++) {
      var subject = subjects[i];
      var movie = {};
      movie["movieId"] = subject.id;
      movie["cover"] = subject.images.large;
      movie["title"] = subject.title;
      movie["rating"] = { stars: commonjs.convertStarsToStarsArray(subject.rating.stars), average: subject.rating.average };
      movies.push(movie);
    }

    var obj = {};
    obj["movies"] = movies;
    obj["categoryTitle"] = data.title;

    if (key === "in_theaters") {
      this.setData({ in_theaters: obj });
    } else if (key === "coming_soon") {
      this.setData({ coming_soon: obj });
    } else if (key === "top250") {
      this.setData({ top250: obj });
    }
  },
  onMoreTap: function (event) {
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more/more?category=' + category
    });
  },
  onItemClick(event) {
    var movieId = event.currentTarget.dataset.movieId;
    wx.navigateTo({
      url: 'movie-detail/movie-detail?movieId=' + movieId
    });
  }
})